package com.example.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.SysLoginRecord;
import com.example.demo.entity.SysUser;
import com.example.demo.mapper.SysLoginRecordMapper;
import com.example.demo.mapper.SysUserMapper;
import com.example.demo.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.utils.IpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author ld&zjw
 * @since 2024-01-27
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    SysUserMapper userMapper;

    @Resource
    SysLoginRecordMapper loginRecordMapper;

    @Override
    public SysUser login(SysUser user) {
        SysUser userRes = userMapper.selectOne(
                Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, user.getUsername()).eq(SysUser::getPassword, encryptToMD5(user.getPassword())));
        return userRes;
    }

    @Override
    public Boolean register(SysUser user) {
        SysUser res = userMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, user.getUsername()));
        if (res != null) {
            return false;
        }
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return true;
    }

    @Override
    public boolean save(SysUser user) {
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        int insert = userMapper.insert(user);
        if (insert == 1)
            return true;
        else
            return false;
    }

    @Override
    public int update(SysUser user) {
        return userMapper.updateById(user);
    }

    @Override
    public int update(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public SysUser getById(Long id) {
        SysUser user = userMapper.selectById(id);
        return user;
    }

    @Override
    public Page<SysUser> findPage(Integer pageNum, Integer pageSize, String search) {

        LambdaQueryWrapper<SysUser> wrapper = Wrappers.<SysUser>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(SysUser::getNickName, search);
        }
        Page<SysUser> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return userPage;
    }

    public static String encryptToMD5(String str) {
        return DigestUtils.md5Hex(str);
    }
}
